#include <ctype.h>
#include <fcntl.h>
#include <sys/stat.h>

#include "../lib/tlpi_hdr.h"

int main() {
    char argv1[48], argv2[48];
    scanf("%s", argv1);

    size_t len;
    off_t offset;
    int fd, j;
    char *buf;
    ssize_t numRead, numWritten;

    fd = open(argv1, O_RDWR | O_CREAT,
              S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
    if (fd == -1) {
        errExit("open");
    }

    while (TRUE) {
        scanf("%s", argv2);
        char flag = argv2[0];
        if ('q' == flag) {
            break;
        } else if ('r' == flag || 'R' == flag) {
            len = getLong(&argv2[1], GN_ANY_BASE, argv2);
            buf = malloc(len);
            if (buf == NULL) {
                errExit("malloc");
            }
            numRead = read(fd, buf, len);
            if (numRead == -1) {
                errExit("read");
            }
            if (numRead == 0) {
                printf("%s: end-of-file\n", argv1);
            } else {
                printf("%s: ", argv1);
                for (j = 0; j < numRead; j++) {
                    if (argv1[0] == 'r')
                        printf("%c",
                               isprint((unsigned char)buf[j]) ? buf[j] : '?');
                    else
                        printf("%02x ", (unsigned int)buf[j]);
                }
                printf("\n");
            }
            free(buf);
        } else if ('w' == flag) {
            numWritten = write(fd, &argv1[1], strlen(&argv1[1]));
            if (numWritten == -1) errExit("write");
            printf("%s: wrote %ld bytes\n", argv1, (long)numWritten);
        } else if ('s' == flag) {
            offset = getLong(&argv1[1], GN_ANY_BASE, argv1);
            if (lseek(fd, offset, SEEK_SET) == -1) errExit("lseek");
            printf("%s: seek succeeded\n", argv1);
        } else {
            cmdLineErr("Argument must start with [rRws]: %s\n", argv1);
        }
    }
}